package zmee.pmas.form;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.cache.CacheFactory;
import kd.bos.cache.TempFileCache;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.EntityType;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.datamodel.events.GetEntityTypeEventArgs;
import kd.bos.entity.property.AmountProp;
import kd.bos.exception.KDBizException;
import kd.bos.fileservice.FileService;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.form.FormShowParameter;
import kd.bos.form.control.Control;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.Label;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.LoadCustomControlMetasArgs;
import kd.bos.form.field.AttachmentEdit;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.metadata.dao.MetaCategory;
import kd.bos.metadata.dao.MetadataDao;
import kd.bos.metadata.entity.EntityMetadata;
import kd.bos.metadata.entity.commonfield.DecimalField;
import kd.bos.metadata.entity.commonfield.TextField;
import kd.bos.metadata.form.FormMetadata;
import kd.bos.metadata.form.control.EntryAp;
import kd.bos.metadata.form.control.EntryFieldAp;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.service.ServiceFactory;
import kd.bos.service.metadata.MetadataService;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.pmgt.pmba.formplugin.ProjectKanBanUI;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import zmee.common.allhelper.OccupiedAmountCalculateHelper;
import zmee.entity.BudgetProInfo;

import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author cb
 * @DateTime 2022/11/27 17:37
 * @Description 项目看板、编辑插件,动态添加字段
 */
public class ProjectKanBanUIEx extends ProjectKanBanUI {
    private static final Log logger = LogFactory.getLog(ProjectKanBanUIEx.class);
    private static final FileService fileServiceEx = FileServiceFactory.getAttachmentFileService();
    private static final TempFileCache tempFileCacheEx = CacheFactory.getCommonCacheFactory().getTempFileCache();
    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addClickListeners("zmee_indexentry");
    }

    @Override
    public void click(EventObject evt) {
        super.click(evt);
        Control source = (Control) evt.getSource();
        String key = source.getKey();
        this.changeButtonStyle(key);
        if ("zmee_indexentry".equals(key)) {
            this.setVisibleFlexPanel();
        } else {
            switch (key) {
                case "workspvbuttonap":
                case "basebuttonap":
                case "teambuttonap":
                case "objebuttonap":
                case "fundbuttonap":
                case "contractbuttonap":
                case "progbuttonap":
                    // 设置 考量指标面板 的可见性
                    this.getView().setVisible(Boolean.FALSE, "zmee_flexpanelapflex");
                    break;
                case "profilebuttonap":
                    //带出相关附件
                    click_probuttonap();
                    // 设置 考量指标面板 的可见性
                    this.getView().setVisible(Boolean.FALSE, "zmee_flexpanelapflex");
                    break;
                case "probudgetbuttonap":
                    //点击项目预算按钮时，带出相关信息
                    click_probudgetbuttonap();
                    // 设置 考量指标面板 的可见性
                    this.getView().setVisible(Boolean.FALSE, "zmee_flexpanelapflex");
                    break;
                default:
                    break;
            }
        }
    }

    private void changeButtonStyle(String excludeBtnKey) {
        List<String> buttList = new ArrayList<>();
        buttList.add("basebuttonap");
        buttList.add("teambuttonap");
        buttList.add("objebuttonap");
        buttList.add("fundbuttonap");
        buttList.add("progbuttonap");
        buttList.add("contractbuttonap");
        buttList.add("workspvbuttonap");
        buttList.add("probudgetbuttonap");
        buttList.add("profilebuttonap");
        buttList.add("zmee_indexentry");
        if (buttList.contains(excludeBtnKey)) {
            buttList.remove(excludeBtnKey);
            this.setBtnClickStyle(excludeBtnKey);
            for (String butt : buttList) {
                this.setBtnUnClickStyle(butt);
            }
        }
    }

    private void setBtnClickStyle(String buttonKey) {
        Map<String, Object> ctrl = new HashMap<>();
        ctrl.put("fc", "#5e80eb");
        Map<String, Object> selectedborder = new HashMap<>();
        Map<String, Object> selectedstyle = new HashMap<>();
        selectedborder.put("b", "0px_solid_#000000");
        selectedborder.put("l", "8px_solid_#5e80eb");
        selectedborder.put("r", "0px_solid_#000000");
        selectedborder.put("t", "0px_solid_#000000");
        selectedstyle.put("b", selectedborder);
        ctrl.put("s", selectedstyle);
        this.getView().updateControlMetadata(buttonKey, ctrl);
    }

    private void setBtnUnClickStyle(String buttonKey) {
        Map<String, Object> ctrl = new HashMap<>();
        ctrl.put("fc", "#000000");
        Map<String, Object> selectedborder = new HashMap<>();
        Map<String, Object> selectedstyle = new HashMap<>();
        selectedborder.put("b", "0px_solid_#000000");
        selectedborder.put("l", "0px_solid_#000000");
        selectedborder.put("r", "0px_solid_#000000");
        selectedborder.put("t", "0px_solid_#000000");
        selectedstyle.put("b", selectedborder);
        ctrl.put("s", selectedstyle);
        this.getView().updateControlMetadata(buttonKey, ctrl);
    }


    private void setVisibleFlexPanel() {
        List<String> panelList = new ArrayList<>();
        panelList.add("workspvflexpanelap");
        panelList.add("baseflexpanelap");
        panelList.add("teamflexpanelap");
        panelList.add("objeflexpanelap");
        panelList.add("fundflexpanelap");
        panelList.add("progflexpanelap");
        panelList.add("contractflexpanelap");
        panelList.add("probudgetflexpanelap");
        panelList.add("profileflexpanelap");
        this.getView().setVisible(Boolean.TRUE, "zmee_flexpanelapflex");
        for (String panel : panelList) {
            this.getView().setVisible(Boolean.FALSE, panel);
        }
    }

    @Override
    public void beforeBindData(EventObject e) {
        super.beforeBindData(e);
        beforeBindData_indexentry();
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String operateKey = e.getOperateKey();
        if("refresh".equals(operateKey)){
            click_probudgetbuttonap();
            click_probuttonap();
        }
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
//        click_probudgetbuttonap();
    }

    /**
     * 考量指标
     */
    protected void beforeBindData_indexentry(){
        FormShowParameter formShowParameter = this.getView().getFormShowParameter();
        Map<String, Object> customParams = formShowParameter.getCustomParams();
        EntryAp dynamicEntryAp = createDynamicEntryAp(formShowParameter);
        EntryGrid entryGrid = this.getView().getControl("zmee_flexpanelap");
        List<Control> fieldEdits = dynamicEntryAp.buildRuntimeControl().getItems();
        for (Control fieldEdit : fieldEdits) {
            fieldEdit.setView(this.getView());
            entryGrid.getItems().add(fieldEdit);
        }
        // 考量指标单据体
        DynamicObjectCollection zmeeFlexpanelap = this.getModel().getEntryEntity("zmee_flexpanelap");

        Object proAppId = customParams.get("proAppId");
        // 项目立项
        DynamicObject proApproval = BusinessDataServiceHelper.loadSingle(proAppId, "pmas_pro_approval");
        // 项目
        DynamicObject pro = proApproval.getDynamicObject("pro");
        QFilter qFilter = new QFilter("project.id", QCP.equals, pro.getPkValue());
        // 查询 项目后评价
        DynamicObjectCollection query = QueryServiceHelper.query("pmsc_projectevaluation", "id", new QFilter[]{qFilter});
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (CollectionUtils.isNotEmpty(query)) {
            DynamicObject loadSingle = BusinessDataServiceHelper.loadSingle(query.get(0).get("id"), "pmsc_projectevaluation");
            // 考量指标
            DynamicObjectCollection indexnames = loadSingle.getDynamicObjectCollection("indexentry");
            for (DynamicObject entry : indexnames) {
                DynamicObject indexname = entry.getDynamicObject("indexname");
                BigDecimal standardindex = entry.getBigDecimal("standardindex");
                BigDecimal excellentindex = entry.getBigDecimal("excellentindex");
                BigDecimal prodeclare = entry.getBigDecimal("prodeclare");
                BigDecimal reportdeclare = entry.getBigDecimal("reportdeclare");
                BigDecimal deviationrate = entry.getBigDecimal("deviationrate");
                String explain = entry.getString("explain");
                DynamicObject addNew = zmeeFlexpanelap.addNew();
                addNew.set("zmee_indexname", indexname);
                addNew.set("zmee_standardindex", standardindex);
                addNew.set("zmee_excellentindex", excellentindex);
                addNew.set("zmee_prodeclare", prodeclare);
                addNew.set("zmee_reportdeclare", reportdeclare);
                addNew.set("zmee_deviationrate", deviationrate);
                addNew.set("zmee_explain", explain);
                addNew.set("determine", entry.getString("zmee_textfield"));
            }
        }
        List<List<BigDecimal>> arrayList = new ArrayList<>();
        List<List<BigDecimal>> arrayQList = new ArrayList<>();
        for (DynamicObject object : query) {
            DynamicObject loadSingle = BusinessDataServiceHelper.loadSingle(object.get("id"), "pmsc_projectevaluation");
            // 考量指标
            DynamicObjectCollection indexnames = loadSingle.getDynamicObjectCollection("indexentry");

            List<BigDecimal> objects = new ArrayList<>();
            List<BigDecimal> objectqs = new ArrayList<>();
            for (DynamicObject indexname : indexnames) {
                objects.add(indexname.getBigDecimal("actualvalue"));
                String qStr = indexname.getString("zmee_textfield1");
                BigDecimal qBigDecimal = StringUtils.isEmpty(qStr) ? BigDecimal.ZERO : BigDecimal.valueOf(Long.parseLong(qStr));
                objectqs.add(qBigDecimal);
            }
            arrayList.add(objects);
            arrayQList.add(objectqs);
        }

        for (int i = 0; i < arrayList.size(); i++) {
            String key = "zmee_columns" + i;
            String qKey = "zmee_qcolumns" + i;
            List<BigDecimal> bigDecimals = arrayList.get(i);
            List<BigDecimal> bigDecimalQs = arrayQList.get(i);
            for (int j = 0; j < bigDecimals.size(); j++) {
                DynamicObject dy = zmeeFlexpanelap.get(j);
                dy.set(key, bigDecimals.get(j));
                dy.set(qKey, bigDecimalQs.get(j));
            }
        }
        this.getView().updateView("zmee_flexpanelap");

        // 设置 考量指标面板 的可见性
        this.getView().setVisible(Boolean.FALSE, "zmee_flexpanelapflex");
    }

    @Override
    public void loadCustomControlMetas(LoadCustomControlMetasArgs e) {
        super.loadCustomControlMetas(e);
        // 动态给单据体添加字段
        Map<String, Object> mapEntry = new HashMap<>();
        mapEntry.put("id", "zmee_flexpanelap");
        FormShowParameter source = (FormShowParameter) e.getSource();
        mapEntry.put("columns", this.buildDyncColumns(source));
        e.getItems().add(mapEntry);
    }

    private List<?> buildDyncColumns(FormShowParameter source) {
        EntryAp entryAp = this.createDynamicEntryAp(source);
        List newColumns = (List) entryAp.createControl().get("columns");
        MetadataService metaService = ServiceFactory.getService(MetadataService.class);
        String metadata = metaService.loadClientFormMeta(source.getFormId());
        Map<String, Object> parseObj = JSON.parseObject(metadata);
        JSONArray items = (JSONArray) parseObj.get("items");
        JSONObject jsonObject = (JSONObject) items.get(1);
        JSONArray items1 = (JSONArray) jsonObject.get("items");
        for (Object o : items1) {
            JSONObject o1 = (JSONObject) o;
            Object id = o1.get("id");
            if ("flexpanelap3".equals(id)) {
                JSONArray items2 = (JSONArray) o1.get("items");
                for (Object o2 : items2) {
                    JSONObject o3 = (JSONObject) o2;
                    Object id1 = o3.get("id");
                    if ("zmee_flexpanelapflex".equals(id1)) {
                        JSONArray items3 = (JSONArray) o3.get("items");
                        for (Object o4 : items3) {
                            JSONObject o41 = (JSONObject) o4;
                            Object id2 = o41.get("id");
                            if ("zmee_flexpanelap".equals(id2)) {
                                JSONArray columns = (JSONArray) o41.get("columns");
                                for (int i = 0; i < newColumns.size(); ++i) {
                                    Map map = (Map) newColumns.get(i);
                                    if (i >= 2) {
                                        JSONObject json = (JSONObject) JSON.toJSON(map);
                                        columns.add(json);
                                    }
                                }
                                return columns;
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    private EntryAp createDynamicEntryAp(FormShowParameter formShowParameter) {
        EntryAp entryAp = new EntryAp();
        entryAp.setKey("zmee_flexpanelap");
        Map<String, Object> parentData = formShowParameter.getCustomParams();
        Object proAppId = parentData.get("proAppId");
        DynamicObject proApproval = BusinessDataServiceHelper.loadSingle(proAppId, "pmas_pro_approval");
        // 项目
        DynamicObject pro = proApproval.getDynamicObject("pro");
        QFilter qFilter = new QFilter("project.id", QCP.equals, pro.getPkValue());
        // 查询项目后评价
        DynamicObjectCollection query = QueryServiceHelper.query("pmsc_projectevaluation",
                "id,itemtime", new QFilter[]{qFilter});
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Set<Date> supplierName = new HashSet<>();
        for (DynamicObject dynamicObject : query) {
            Date itemtime = dynamicObject.getDate("itemtime");
            supplierName.add(itemtime);
        }
        List<Date> supplierNames = new ArrayList(supplierName);
        supplierNames.sort(new Comparator<Date>() {
            @Override
            public int compare(Date o1, Date o2) {
                return o1.compareTo(o2);
            }
        });
        Map<String, String> supplierToIdentification = new LinkedHashMap<>();
        Date s;
        String columnKey;
        String qcolumnKey;
        for (int i = 0; i < supplierNames.size(); i++) {
            s = supplierNames.get(i);
            String format = sdf.format(s);
            columnKey = "zmee_columns" + i;
            supplierToIdentification.put(format + "：实际定量值", columnKey);
            qcolumnKey = "zmee_qcolumns" + i;
            supplierToIdentification.put(format + "：实际定性值", qcolumnKey);
        }
        String q;
        for (String value : supplierToIdentification.keySet()) {
            q = value;
            columnKey = supplierToIdentification.get(q);
            EntryFieldAp fieldAp = new EntryFieldAp();
            fieldAp.setId(columnKey);
            fieldAp.setKey(columnKey);
            fieldAp.setName(new LocaleString(q));
            fieldAp.setWidth(new LocaleString("220px"));
            fieldAp.setFireUpdEvt(true);
            TextField textField = new TextField();
            textField.setId(columnKey);
            textField.setName(new LocaleString(columnKey));
            textField.setKey(columnKey);
            //DecimalField decimalField = new DecimalField();
            //decimalField.setId(columnKey);
            //decimalField.setScale(2);
            //decimalField.setName(new LocaleString(columnKey));
            //decimalField.setZeroShow(true);
            //decimalField.setPrecision(23);
            //decimalField.setKey(columnKey);
            MainEntityType mainType = EntityMetadataCache.getDataEntityType("pmba_projectkanban");
            FormMetadata formMeta = (FormMetadata) MetadataDao.readRuntimeMeta(MetadataDao.getIdByNumber(mainType.getName(), MetaCategory.Form), MetaCategory.Form);
            EntityMetadata entityMetadata = (EntityMetadata) MetadataDao.readRuntimeMeta(formMeta.getEntityId(), MetaCategory.Entity);
            textField.setEntityMetadata(entityMetadata);
            fieldAp.setField(textField);
            entryAp.getItems().add(fieldAp);
        }
        return entryAp;
    }

    @Override
    public void getEntityType(GetEntityTypeEventArgs e) {
        MainEntityType oldMainType = e.getOriginalEntityType();
        MainEntityType newMainType;
        try {
            newMainType = (MainEntityType) oldMainType.clone();
        } catch (CloneNotSupportedException var25) {
            throw new KDBizException(var25.getMessage());
        }
        EntityType entryType = newMainType.getAllEntities().get("zmee_flexpanelap");
        FormShowParameter formShowParameter = this.getView().getFormShowParameter();
        Map<String, Object> parentData = formShowParameter.getCustomParams();

        Object proAppId = parentData.get("proAppId");
        DynamicObject proApproval = BusinessDataServiceHelper.loadSingle(proAppId, "pmas_pro_approval");
        // 项目
        DynamicObject pro = proApproval.getDynamicObject("pro");
        QFilter qFilter = new QFilter("project.id", QCP.equals, pro.getPkValue());
        // 查询项目后评价
        DynamicObjectCollection query = QueryServiceHelper.query("pmsc_projectevaluation",
                "id,itemtime", new QFilter[]{qFilter});
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 名称 set集合
        Set<Date> supplierName = new LinkedHashSet<>();
        for (DynamicObject object : query) {
            Date itemtime = object.getDate("itemtime");
            supplierName.add(itemtime);
        }

        List<Date> supplierNames = new ArrayList(supplierName);
        Map<String, String> supplierToIdentification = new LinkedHashMap<>();
        Date s;
        String columnKey;
        String qcolumnKey;
        for (int i = 0; i < supplierNames.size(); i++) {
            s = supplierNames.get(i);
            String format = sdf.format(s);
            columnKey = "zmee_columns" + i;
            supplierToIdentification.put(format + "：实际值", columnKey);
            qcolumnKey = "zmee_qcolumns" + i;
            supplierToIdentification.put(format + "：实际定性值", qcolumnKey);
        }

        for (String key : supplierToIdentification.keySet()) {
            AmountProp amountProp = new AmountProp();
            amountProp.setName(supplierToIdentification.get(key));
            amountProp.setDisplayName(new LocaleString(key));
            entryType.registerSimpleProperty(amountProp);
        }
        newMainType.createPropIndexsNoCache();
        e.setNewEntityType(newMainType);
    }

    /**
     * 项目预算带出
     */
    protected void click_probudgetbuttonap(){
        Map<String, Object> param = this.getView().getFormShowParameter().getCustomParams();
        Object id = param.get("proAppId");
        if (id != null) {
            DynamicObject proAppDy = BusinessDataServiceHelper.loadSingle(id, "pmas_pro_approval");
            if(proAppDy == null){
                return;
            }
            DynamicObject proDy = proAppDy.getDynamicObject("pro");
            if(proDy == null){
                return;
            }
            Long projectId = proDy.getLong("id");

            BudgetProInfo budgetProInfo = new BudgetProInfo(projectId);
            Map<Long, Map<Integer, BigDecimal>> occupiedAmountMap = OccupiedAmountCalculateHelper.calculateOccupiedBudgetitemAmount(projectId,false,budgetProInfo);
            Map<Long, Map<Integer, BigDecimal>> proPayAmountMap = OccupiedAmountCalculateHelper.calculateProPayAmt(projectId,false,budgetProInfo);
            Map<Long, Map<Integer, BigDecimal>> budgetAmountMap = OccupiedAmountCalculateHelper.calculateBudgetAmt(projectId,false,budgetProInfo);
            //根据预算项带出已占用金额
            DynamicObject dataEntity = this.getModel().getDataEntity(true);
            DynamicObjectCollection outBudgetEntryDyCo = dataEntity.getDynamicObjectCollection("outbudgetentry");
            //获取期间
            Integer dateOfYear = OccupiedAmountCalculateHelper.getDateOfYear(new Date());
            for (int i = 0; i < outBudgetEntryDyCo.size(); i++) {
                DynamicObject outBudgetEntryDy = outBudgetEntryDyCo.get(i);
                BigDecimal occAmt = BigDecimal.ZERO;
                BigDecimal proPayAmt = BigDecimal.ZERO;
                BigDecimal budGetAmt = BigDecimal.ZERO;
                //获取预算项生效id
                Long budgetValidId = budgetProInfo.getBudgetValidId(outBudgetEntryDy.getLong("id"), true, dateOfYear);
                Map<Integer, BigDecimal> projectDyBudGetMap = occupiedAmountMap.get(budgetValidId);
                Map<Integer, BigDecimal> proPayMap = proPayAmountMap.get(budgetValidId);
                Map<Integer, BigDecimal> budGetMap = budgetAmountMap.get(budgetValidId);
                if(projectDyBudGetMap != null){
                    occAmt = projectDyBudGetMap.get(dateOfYear);
                }
                if(proPayMap != null){
                    proPayAmt = proPayMap.get(dateOfYear);
                }
                if(budGetMap != null){
                    budGetAmt = budGetMap.get(dateOfYear);
                }
                this.getModel().setValue("zmee_yearamt",occAmt,i);
                this.getModel().setValue("zmee_yearpayamt",proPayAmt,i);
                this.getModel().setValue("zmee_yearbudgetamt",budGetAmt,i);
            }

            //项目预算总额 - zmee_probudgetamt
            BigDecimal projcetbugamt = proAppDy.getBigDecimal("projcetbugamt");
            setLabelTextBigDecimal("zmee_probudgetamt",projcetbugamt);
            //已占用金额 - zmee_occupyamt
            BigDecimal occupyamt = calculTotalFromMap(occupiedAmountMap);
            setLabelTextBigDecimal("zmee_occupyamt",occupyamt);
            //已付款金额 - zmee_payamt
            BigDecimal proPayamt = calculTotalFromMap(proPayAmountMap);
            setLabelTextBigDecimal("zmee_payamt",proPayamt);
            //剩余金额 - zmee_residualamt = 项目预算总额 - 已占用金额
            BigDecimal residualAmt = projcetbugamt.subtract(occupyamt);
            setLabelTextBigDecimal("zmee_residualamt",residualAmt);
            //剩余比例 - zmee_residualpercent = 剩余金额/项目预算总额
            if(projcetbugamt.compareTo(BigDecimal.ZERO) != 0){
                BigDecimal residualPercent = residualAmt.divide(projcetbugamt,4,BigDecimal.ROUND_HALF_UP);
                setLabelTextBigDecimal("zmee_residualpercent",residualPercent);
            }
        }
    }

    /**
     * 附件审批
     */
    protected void click_probuttonap(){
        Map<String, Object> param = this.getView().getFormShowParameter().getCustomParams();
        Object approvalId = param.get("proAppId");
        QFilter approvalQFilter = new QFilter("id",QCP.equals,approvalId);
        QFilter auditQFilter = new QFilter("proapp",QCP.equals,approvalId);
        //项目发文附件 approvalfileentry 附件 apppattachfile 关联单据 approvalbillno
        DynamicObjectCollection approvalFileEntryDyCo = this.getModel().getEntryEntity("approvalfileentry");
        approvalFileEntryDyCo.clear();
        apppattachFileImport("pmas_pro_approval",approvalQFilter,"createtime","zmee_attachmentpanelap","apppattachfile",
                "approvalbillno","项目立项",approvalFileEntryDyCo);//项目立项 立项发文附件 zmee_attachmentpanelap

        //评审方案/意见/批复文件 auditfileentry 附件 auditattachfile 关联单据 auditbillno
        DynamicObjectCollection auditFileEntryDyCo = this.getModel().getEntryEntity("auditfileentry");
        auditFileEntryDyCo.clear();
        apppattachFileImport("pmas_pro_approval",approvalQFilter,"createtime","zmee_attachmentpanelap1","auditattachfile",
                "auditbillno","项目立项",auditFileEntryDyCo);//项目立项 方案或批复文件附件面板 zmee_attachmentpanelap1
        apppattachFileImport("pmas_proj_audit",auditQFilter,"createtime","zmee_attachmentpanelap2","auditattachfile",
                "auditbillno","立项审批",auditFileEntryDyCo);//立项审批 环能本部评审附件面板 zmee_attachmentpanelap2
        apppattachFileImport("pmas_proj_audit",auditQFilter,"createtime","zmee_attachmentpanelap1","auditattachfile",
                "auditbillno","立项审批",auditFileEntryDyCo);//立项审批 项目批复附件面板 zmee_attachmentpanelap1

        //环能发文总部附件/中大总部批复文件 proauditfileentry 附件 proauditattachfile 关联单据 proauditbillno
        DynamicObjectCollection proauditFileEntryDyCo = this.getModel().getEntryEntity("proauditfileentry");
        proauditFileEntryDyCo.clear();
        apppattachFileImport("pmas_proj_audit",auditQFilter,"createtime","zmee_attachmentpanelap","proauditattachfile",
                "proauditbillno","立项审批",proauditFileEntryDyCo);//立项审批 请示集团附件面板 zmee_attachmentpanelap

        this.getModel().updateEntryCache(approvalFileEntryDyCo);
        this.getModel().updateEntryCache(auditFileEntryDyCo);
        this.getModel().updateEntryCache(proauditFileEntryDyCo);
        this.getView().updateView("approvalfileentry");
        this.getView().updateView("auditfileentry");
        this.getView().updateView("proauditfileentry");
    }

    /**
     * 附件信息引入
     */
    private void apppattachFileImport(String formId,QFilter filter,String orderBy,String attachKey,
                                      String entryAttachStr,String entryBillnoStr,String billName,DynamicObjectCollection entryDyCo){
        List<Map<String, Object>> attachments;
        ORM orm = ORM.create();
        String name;
        String tempUrl;
        Iterator var109;
        StackTraceElement[] stackTraces;
        DynamicObject fileObject;
        DynamicObjectType fileDyTy = entryDyCo.getDynamicObjectType();
        //1、获取元件信息
        DynamicObject[] formDyArr = BusinessDataServiceHelper.load(formId, "id,billno,createtime", new QFilter[]{filter}, String.format("%s desc",orderBy));
        if (formDyArr != null && formDyArr.length > 0) {
            DynamicObject formDy = formDyArr[0];
            attachments = AttachmentServiceHelper.getAttachments(formId, formDy.getPkValue(), attachKey);

            if (attachments != null && attachments.size() > 0) {
                long[] ids = orm.genLongIds(EntityMetadataCache.getDataEntityType("bd_attachment"), attachments.size());
                int idIndex = 0;
                Iterator var87 = attachments.iterator();

                while(var87.hasNext()) {
                    Map<String, Object> attach = (Map)var87.next();
                    name = (String)attach.get("url");
                    tempUrl = (String)attach.get("name");
                    tempUrl = saveAsTempFile(name, tempUrl);
                    attach.put("uid", String.valueOf(ids[idIndex++]));
                    attach.put("url", tempUrl);
                }

                DynamicObject fileDy = new DynamicObject(fileDyTy);
                fileDy.set("id", formDy.getPkValue());
                fileDy.set(entryBillnoStr, formDy.getString("billno"));
                DynamicObjectCollection attachCols = fileDy.getDynamicObjectCollection(entryAttachStr);
                AttachmentEdit attachmentField = (AttachmentEdit)this.getView().getControl(entryAttachStr);

                Object attachFileObjs;
                try {
                    attachFileObjs = attachmentField.getAttachmentModel().saveAttachments(attachmentField.getModel(), this.getView().getPageId(), this.getModel().getDataEntityType().getName(), attachments);
                } catch (Exception var53) {
                    stackTraces = var53.getStackTrace();
                    StringBuilder sb = new StringBuilder();
                    StackTraceElement[] var131 = stackTraces;
                    idIndex = stackTraces.length;

                    for(int var137 = 0; var137 < idIndex; ++var137) {
                        StackTraceElement stackTrace = var131[var137];
                        sb.append(stackTrace.toString()).append("\r\n");
                    }

                    logger.error(String.format("apppattachFileImport.initProFileData %s", sb.toString()));
                    this.getView().showTipNotification(String.format("%s文件%s附件传输错误，请通过关联单据超链查看附件。", billName,formDy.getString("billno")));
                    attachFileObjs = new ArrayList();
                }

                Set<Object> attachSet = new HashSet(((List)attachFileObjs).size());
                var109 = ((List)attachFileObjs).iterator();

                while(var109.hasNext()) {
                    fileObject = (DynamicObject)var109.next();
                    attachSet.add(fileObject.getPkValue());
                }

                QFilter[] filters = new QFilter[]{new QFilter("id", "in", attachSet)};
                DynamicObjectCollection attachFileCols = orm.query("bd_attachment", filters);
                Iterator var133 = attachFileCols.iterator();

                while(var133.hasNext()) {
                    DynamicObject attachFileObj = (DynamicObject)var133.next();
                    attachCols.addNew().set("fbasedataid", attachFileObj);
                }

                if (attachCols.size() > 0) {
                    fileDy.set(entryAttachStr, attachCols);
                }
                entryDyCo.add(fileDy);
            }
        }
    }

    private void setLabelTextBigDecimal(String labelStr,BigDecimal amt){
        Label probudgetamtLabel = this.getControl(labelStr);
        probudgetamtLabel.setText(String.valueOf(amt.setScale(2, BigDecimal.ROUND_HALF_UP)));
    }

    private BigDecimal calculTotalFromMap(Map<Long, Map<Integer, BigDecimal>> map){
        BigDecimal totalAmt = BigDecimal.ZERO;
        for(Map<Integer, BigDecimal> amtMap : map.values()){
            for (BigDecimal amt : amtMap.values()) {
                totalAmt = totalAmt.add(amt);
            }
        }
        return totalAmt;
    }

    private String saveAsTempFile(String url, String name) {
        String path = url.split("download.do\\?path=")[1];
        path = path.substring(0, path.lastIndexOf("&kdedcba"));
        InputStream inputStream = fileServiceEx.getInputStream(path);
        String tempUrl = tempFileCacheEx.saveAsUrl(name, inputStream, 7200);
        String address = RequestContext.get().getClientFullContextPath();
        if (!address.endsWith("/")) {
            address = address + "/";
        }

        tempUrl = address + tempUrl;
        return tempUrl;
    }
}